<template>
  <div class="platform">
    <div class="left">
      <ConfigForm :receivedCoods="coodsFromCanvasContainer" />
    </div>
    <div class="right f-r-a-c">
      <CanvasContainer @updateCoods="onUpdateCoods" canvasId="myCanvas" :width="width" :height="height" :radius="radius"
        :dpr="dpr" />
      <CanvasRecorder canvasId="myCanvas" :width="width" :height="height" />
    </div>
  </div>
</template>

<script setup>
import HelloWorld from "./components/HelloWorld.vue";
import CanvasContainer from "./components/CanvasContainer.vue";
import CanvasRecorder from "./components/CanvasRecorder.vue";
import ConfigForm from "./components/ConfForm.vue";
import { provide, ref, watch } from "vue";

const getLayout = (type) => {
  return localStorage.getItem(type);
}

const setLayout = (type, val) => {
  console.log(type, val)
  localStorage.setItem(type, val);
}

let width = ref(getLayout('width') || 375);
let height = ref(getLayout('height') || 750);
let dpr = ref(getLayout('dpr') || 4);
let radius = ref(getLayout('radius') || 16);
let helpLine = ref(false);
let coodsFromCanvasContainer = ref(null); //接收来自画布容器的坐标，可用于表单中，自动更新某个元素的位置

// 监听 width、height 变化，重新调用 initCanvas 方法。
watch(() => width.value, (newV) => {
  setLayout('width', newV)
})
watch(() => height.value, (newV) => {
  setLayout('height', newV)
})
watch(() => radius.value, (newV) => {
  setLayout('radius', newV)
})
watch(() => dpr.value, (newV) => {
  setLayout('dpr', newV)
})


let localSavedConfig = localStorage.getItem("drawConfig");
// let localSavedConfig = localStorage.getItem("config");
localSavedConfig = localSavedConfig ? JSON.parse(localSavedConfig) : [];
let drawConfig = ref(localSavedConfig);

function addDrawConfig(config) {
  drawConfig.value.push(config);
}

function loadDrawConfigs(configs) {
  drawConfig.value = [...configs];
}

function exportConfig() {
  localStorage.setItem("drawConfig", JSON.stringify(drawConfig.value));
  console.log("✅ 已导出配置到 localStorage，请自行提取。");
}

function onUpdateCoods(data) {
  console.log('get coods:', data)
  coodsFromCanvasContainer.value = data;
}

provide("width", width);
provide("height", height);
provide("radius", radius);
provide("dpr", dpr);
provide("helpLine", helpLine);
provide("drawConfig", drawConfig); // 绘制元素的数据
provide("addDrawConfig", addDrawConfig); //追加配置项
provide("loadDrawConfigs", loadDrawConfigs); //加载新的配置列表
provide("exportConfig", exportConfig);

</script>
<style lang="less" scoped>
.platform {
  box-sizing: border-box;
  padding: 15px;
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  position: relative;
  height: 100vh;
  max-height: 100vh;
  overflow-y: auto;

  .left {
    background: #fff;
    flex: 2;
    height: 100%;
    overflow-y: auto;
    box-sizing: border-box;
    border-radius: 8px;
  }

  .right {
    overflow-y: auto;
    box-sizing: border-box;
    background: #f5f5f5;
    flex: 5;
    height: 100%;
  }
}
</style>
